package com.leyou.gateway.filter;

import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 判断用户是否登陆，只有登陆才可以操作
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})//将该配置类注入到spring ioc中
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private FilterProperties filterProperties;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        //初始化zuul上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        //获取路径
        String url = request.getRequestURL().toString();
        //循环遍历集合，是否包含白名单
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(StringUtils.contains(url,allowPath)){
                //不允许run方法，直接放行
                return false;
            }
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //初始化zuul上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        //获取cookie
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        //判断token
        if(StringUtils.isBlank(token)){
            //用户未登录,不进行转发
            context.setSendZuulResponse(false);
            //返回状态码
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());

        }
        try {
            //获取userInfo,如果不报错就证明用户已登录
            JwtUtils.getInfoFromToken(token,jwtProperties.getPublicKey());
        }catch (Exception e){
            e.printStackTrace();
            //用户未登录,不进行转发
            context.setSendZuulResponse(false);
            //返回状态码
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
